
/*
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

package bgtp;

import java.util.*;
import java.lang.*;
import java.io.IOException;
import java.lang.Thread;
import java.util.UUID;

//прохождение регистрации
//или аутентификации
public class Registrator extends Thread
{
    private Vector<OverHTTP>	adepts;
    private BGTPmm		mainModule;

    public Registrator(BGTPmm boss)
    {
	adepts	   = new Vector<OverHTTP>();
	mainModule = boss;
    }
    
     /**
     *произвести регистрацию. вызываться и обрабатываться 
     *должен клиентским кодом до запуска потока протокола
     *@param myId указывает id данного клиента. может бытьт 'null' тогда резистрируется новый клиент
     *@param clt соединение с сервером
     *@param logger экземпляр логгера
     *@return идентификатор зарегистрированного клиента
     */
    public static String doRegistration(String myId, OverHTTP clt, BGTPLog logger)
    {
	TreeMap<String, String>	response = new TreeMap<String, String>();
	TreeMap<String, String>	request	 = null;
	String			guid	 = null;

	response.put("ReqType", "GET / HTTP/1.1");
	response.put("Action", "Register");
	response.put("GUID", myId);
	
	try
	    {
		clt.send(response);
		request = clt.recv();
	    }
	catch(IOException ioe)
	    {
		//полагаем порвался коннект
		logger.error("doRegistration", "Registration fail. Connection break");
		return null;
	    }

	if(request == null)
	    {
		logger.error("doRegistration", "Registration fail. No response");
 		return null;
	    }

	//чтото приняли в ответ
	if(request.get("ReqType").equals("HTTP/1.1 200 OK") == false)
	    {
		logger.error("doRegistration", "Registration fail");
		//logger.debug("run", "{200 OK HTTP/1.1} != {"+request.get("ReqType")+"}");
		for(String key:request.keySet())
		    {
			System.out.println(key+": "+request.get(key));
		    }
		logger.debug("sendBreak", "Shutdown");
		response.clear();
		response.put("ReqType", "HTTP/1.1 200 OK");
		response.put("Action", "Shutdown");
		response.put("GUID", guid);
		
		try
		    {
			clt.send(response);
		    }
		catch(IOException ioe)
		    {
			ioe.printStackTrace();
			return null;
		    }
		return null;
	    }
	//logger.debug("run", "guid="+guid);
	guid = request.get("GUID");
	response.clear();
	response.put("ReqType", "HTTP/1.1 200 OK");
	response.put("Action", "Accepted");
	response.put("GUID", guid);
	
	try
	    {
		clt.send(response);
	    }
	catch(IOException ioe)
	    {
		//бида бида
		logger.error("doRegistration", "break on success");
		guid = null;
	    }
	logger.debug("doRegistration", "return");
	return guid;
    }

    public void newAdept(OverHTTP oh)
    {
	synchronized(adepts)
	    {
		adepts.add(oh);
	    }
    }

    public void run()
    {
	//проверка и регистрация желающих
	Vector<OverHTTP>	tmp;
	UUID			uuid;
	String			randomUUIDString;
	TreeMap<String, String> reqresp;
	boolean			mustRun = true;

	while(mustRun)
	    {
		//System.out.println("==========Registrator==========");
		if(adepts.size() > 0)
		    {
			synchronized(adepts)
			    {
				tmp    = adepts;
				adepts = new Vector<OverHTTP>();
			    }

		
			for(OverHTTP chnl: tmp)
			    {
				try
				    {
					reqresp = chnl.recv();

					//если гуид есть то отправим обратно с океем если нет то создаим
					if(reqresp.get("GUID").equals("NULL") == true)
					    {
						uuid		 = UUID.randomUUID();
						randomUUIDString = uuid.toString();
					    }
					else if(mainModule.workerExist(reqresp.get("GUID")) == true)
					    {
						randomUUIDString = reqresp.get("GUID");
					    }
					else
					    {
						reqresp.clear();
						reqresp.put("ReqType", "HTTP/1.1 500 Protocol error");
						reqresp.put("GUID", "NOGUID");
						reqresp.put("Action", "Error");
						chnl.send(reqresp);
						chnl.close();
						continue;
					    }

					reqresp.clear();
					reqresp.put("ReqType", "HTTP/1.1 200 OK");
					reqresp.put("GUID", randomUUIDString);
					reqresp.put("Action", "Registered");
					chnl.send(reqresp);

					mainModule.registerWorker(randomUUIDString, 
								  new BGTPWorker(chnl, 
										 mainModule, 
										 randomUUIDString));
				    }	
				catch(IOException ioe)
				    {
					ioe.printStackTrace();
					chnl.close();
					continue;
				    }
			    }
		    }
		else
		    {
			try
			    {
				Thread.sleep(100);
			    }
			catch(InterruptedException ie)
			    {
				ie.printStackTrace();
				break;
			    }
		    }
	    }
    }
}